<template>
  <div>
    <LayoutHeader />

    <UMain>
      <slot />
    </UMain>

    <LayoutFooter />

    <ClientOnly>
      <UContentSearch ref="contentSearchRef" :files="files" :navigation="navigation" />
    </ClientOnly>
  </div>
</template>

<script setup lang="ts">
  import { articleAPI } from '~/apis/article'
  import type { ArticleParams, ArticlePageParams } from '~/apis/article/model'
  import type { BlogPost } from '~/types'

  const { data: navigation } = await useAsyncData('navigation', () => fetchContentNavigation(), {
    default: () => []
  })
  const article = ref<BlogPost[]>([])
  const params: ArticlePageParams = reactive({
    keyword: '',
    status: 'Published',
    pageNum: 1,
    pageSize: 5
  })
  const { data } = await articleAPI.page(params)

  if (data.value) {
    navigation.value.forEach(v => {
      if (v._path === '/article') {
        v.children = data.value?.list.map(item => {
          return {
            title: item.title,
            _path: `/article/detail/${item.id}`
          }
        })
      }
    })
    article.value = data.value.list.map(item => transformPost(item))
  }
  const contentSearchRef = ref<HTMLElement & { commandPaletteRef: any; isOpen: Ref<boolean> }>()
  const debouncedFn = useDebounceFn(searchList, 300)
  const clearFile = () => {
    setTimeout(() => {
      files.value = article.value
    }, 200)
  }
  watchEffect(() => {
    let watch1: any
    if (contentSearchRef.value && contentSearchRef.value.isOpen) {
      nextTick(() => {
        watchEffect(() => {
          if (
            contentSearchRef.value?.commandPaletteRef &&
            contentSearchRef.value?.commandPaletteRef.query
          ) {
            debouncedFn(contentSearchRef.value?.commandPaletteRef.query)
          } else {
            clearFile()
          }
        })
      })
    } else {
      watch1 && watch1()
    }
  })

  const files = ref<BlogPost[]>([])
  async function searchList(str: string) {
    const params: ArticleParams = reactive({
      keyword: str,
      status: 'Published'
    })
    const { data: searchData } = await articleAPI.search(params)
    files.value = searchData.value ? searchData.value.map(item => transformPost(item)) : []
  }

  provide('navigation', navigation)
</script>
